package com.solution.wx.product.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.solution.admin.coupon.constants.CouponConstants;
import com.solution.admin.coupon.entity.CouponEntity;
import com.solution.admin.coupon.service.CouponService;
import com.solution.admin.home.entity.SiteConfigItemEntity;
import com.solution.admin.home.entity.SiteModuleEntity;
import com.solution.admin.home.service.SiteConfigItemService;
import com.solution.admin.home.service.SiteModuleService;
import com.solution.admin.product.entity.ProductBrandEntity;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.entity.ProductCategoryPropertyFilterEntity;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductImageEntity;
import com.solution.admin.product.entity.ProductPriceEntity;
import com.solution.admin.product.entity.ProductPropertyEntity;
import com.solution.admin.product.entity.ProductPropertyRelaEntity;
import com.solution.admin.product.entity.ProductSpecCompositionEntity;
import com.solution.admin.product.entity.ProductSpecRelaEntity;
import com.solution.admin.product.service.ProductBrandService;
import com.solution.admin.product.service.ProductCategoryPropertyFilterService;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.product.service.ProductImageService;
import com.solution.admin.product.service.ProductPriceService;
import com.solution.admin.product.service.ProductPropertyRelaService;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.promotion.constants.PromotionConstants;
import com.solution.admin.promotion.entity.PromotionEntity;
import com.solution.admin.promotion.entity.PromotionProductEntity;
import com.solution.admin.promotion.entity.PromotionRuleDiscountEntity;
import com.solution.admin.promotion.entity.PromotionRuleGiftEntity;
import com.solution.admin.promotion.entity.PromotionRuleReduceEntity;
import com.solution.admin.promotion.entity.PromotionRulesEntity;
import com.solution.admin.promotion.service.PromotionProductService;
import com.solution.admin.promotion.service.PromotionService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.service.OrderEvaluationService;
import com.solution.wx.common.constants.PublicConstants;
import com.solution.wx.core.util.WechatUtil;
import com.solution.wx.my.service.UserFavoriteService;
import com.solution.wx.product.service.ProductBrowseRecordService;

/**
 * 微信端商品查询控制层
 * @author llp
 */
@RequestMapping("/wx/product")
@Controller("wxProductSearchController")
public class ProductSearchController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(ProductSearchController.class);
	
	@Autowired
	private ProductBrandService productBrandService;
	
	@Autowired
	private ProductCategoryPropertyFilterService productCategoryPropertyFilterService;

	@Autowired
	private ProductCategoryService productCategoryService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductPriceService productPriceService;
	
	@Autowired
	private ProductPropertyRelaService productPropertyRelaService;
	
	@Autowired
	private ProductImageService productImageService;
	
	@Autowired
	private SiteConfigItemService siteConfigItemService;
	
	@Autowired
	private PromotionProductService promotionProductService;
	
	@Autowired
	private PromotionService promotionService;
	
	@Autowired
	private UserFavoriteService userFavoriteService;
	
	@Autowired
	private ProductBrowseRecordService productBrowseRecordService;
	
	@Autowired
	private CouponService couponService;
	
	@Autowired
	private SiteModuleService siteModuleService;

	@Autowired
	private OrderEvaluationService orderEvaluationService;
	
	
	
	/**
	 * 微信端商品分类搜索页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/category_search")
	public String listProductListPageByCategory(HttpServletRequest request , HttpServletResponse response){
		// 请求参数回现到页面用的于第二次查询
		Map<String, String> hiddenParamMap = new HashMap<String, String>();
		// 同步异步请求标志(异步请求，返回json数据通过response.getWirter().write 刷入页面)
		String requestType = request.getParameter("requestType");
		
		request.setAttribute(PublicConstants.CURRENT_PAGE_KEY, PublicConstants.PAGE_CATEGORY);
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		String categoryId = request.getParameter("categoryId");
		String categoryPath = request.getParameter("categoryPath");
		String brandIds = request.getParameter("brandIds");
		param.put("categoryId", categoryId) ;
		param.put("categoryPath", categoryPath);
		param.put("brandIds", brandIds);
		request.setAttribute("parentCategoryId", null == request.getParameter("parentCategoryId") ? categoryId : request.getParameter("parentCategoryId"));
		
		hiddenParamMap.put("categoryId", categoryId);
		hiddenParamMap.put("categoryPath", categoryPath);
		hiddenParamMap.put("parentCategoryId", request.getParameter("parentCategoryId"));
		
		// 查询参数
		// 【1】、查询所有商品类型
		List<ProductCategoryEntity> topCategoryList = productCategoryService.listProductCategoryForIndex(param);
		if(topCategoryList !=null && topCategoryList.size() > 0){
			for (ProductCategoryEntity category : topCategoryList) {
				if(StringUtil.isNotEmpty(category.getSubCategoryListStr())){
					List<ProductCategoryEntity> tmpCategoryList = JSONArray.parseArray("["+category.getSubCategoryListStr()+"]", ProductCategoryEntity.class);
					category.setSubCategoryList(tmpCategoryList);
				}
			}
		}
		request.setAttribute("topCategoryList", topCategoryList);
		
		// 【关键字查询】查询商品列表（模糊匹配商品名称 or 类型名称 or 品牌名称）
		// 【筛选项】品牌查询|类型查询|筛选项查询
		
		String pageNumStr = request.getParameter("pageNum");
		if(StringUtil.isEmpty(pageNumStr)){
			pageNumStr = "1";
		}
		int pageNum = Integer.parseInt(pageNumStr);
        int numPerPage = 20;
        PageParam pageParam = super.getPageParam(request);
        pageParam.setPageNum(pageNum);
        pageParam.setNumPerPage(numPerPage);

		// 品牌
		if (StringUtil.isNotEmpty(brandIds)) {
			param.put("brandIds", "(" + brandIds + ")");
			// 添加筛选条件
			for (String brandIdStr : brandIds.split(",")) {
				hiddenParamMap.put(brandIdStr, "1");
			}
		}
		
        String searchKey = request.getParameter("searchKey");
        request.setAttribute("searchKey", searchKey);
        param.put("customerLevel", getCustomerLevel());
        param.put("isLogin", isLogin(request)? "1" : "0");
        param.put("customerId", getCustomerId());
        param.put("searchKey", searchKey);
		PageBean pageBean = productService.listProductPageForIndex(pageParam, param);
		List<ProductEntity> productList = (List)pageBean.getRecordList();
		
		formatProductPrice(productList);
		// 如果是异步，直接写response
		if("sync".equals(requestType)){
			try {
				response.getWriter().write(JSONObject.toJSON(pageBean).toString());
				response.getWriter().flush();
				response.getWriter().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//【2】查询品牌,显示所有品牌
		param.put("categoryIds", null);
		List<ProductBrandEntity> brandList = productBrandService.listAllBrandForWXIndex(param);
		request.setAttribute("brandList", brandList);
		request.setAttribute("productList", productList);
		request.setAttribute("pageBean", pageBean);
		request.setAttribute("hiddenParamMap", hiddenParamMap);
		return "wx/product/product_category";
	}
	
	/**
	 * 格式化商品价格
	 * @param productList
	 */
	private void formatProductPrice(List<ProductEntity> productList){
		// 初始化价格显示
		DecimalFormat df = new DecimalFormat("#.00");
		if(productList != null && productList.size() > 0){
			for (ProductEntity product : productList) {
				if(product.getProductPrice() != null){
					String[] prices = df.format(product.getProductPrice()).split("\\.");
					product.setProductPriceInteger(prices[0]);
					product.setProductPriceDecimal(prices[1]);
				}
			}
		}
	}

	
	
	
	/**
	 * 微信端商品列表搜索页面
	 * 关键字查询  / 筛选项查询
	 * @param request
	 * @return
	 */
	@RequestMapping("/search")
	public String listProductListPage(HttpServletRequest request , HttpServletResponse response, Model model){
		// 请求参数回现到页面用的于第二次查询
		Map<String, String> hiddenParamMap = new HashMap<String, String>();
		// 用于界面回显参数
		Map<String, Object> requestParamMap = new HashMap<String, Object>();
		// 同步异步请求标志(异步请求，返回json数据通过response.getWirter().write 刷入页面)
		String requestType = request.getParameter("requestType");
		// 查询参数
		Map<String, Object> param = new HashMap<String, Object>();
		
		// 搜索关键字（根据商品分类查询）
		String productSearchKey = null != request.getParameter("searchKey") ? request.getParameter("searchKey").trim() : null;
		// 商品分类
		String productCategoryId = request.getParameter("categoryId");
		// 筛选项查询条件
		String propertyFilter = request.getParameter("propertyFilter");
		// 排序
		String sortField = request.getParameter("sortField");
		if (StringUtil.isEmpty(sortField)) {
			sortField = "SORT_NO";
		}
		String sortType = request.getParameter("sortType");
		if (StringUtil.isEmpty(sortType)) {
			sortType = " ASC ";
		}
		// 价格(最低价-最高价)
		String minPrice = request.getParameter("minPrice");
		String maxPrice = request.getParameter("maxPrice");
		// 品牌
		String brandId = request.getParameter("brandId");
		String brandIds = request.getParameter("brandIds");
		request.setAttribute("brandIds", brandIds);
		
		//分类 ID 集合
		List<Long> categoryIdList = new ArrayList<Long>();
		if (StringUtil.isNotNull(productCategoryId)) {
			String[] categoryIdArr = productCategoryId.split(",");
			for (String categoryId : categoryIdArr) {
				categoryIdList.add(Long.parseLong(categoryId));
			}
		}
		/** 微信商品查询以关键字、价格区间、品牌 ，如果3者为空，则显示全部*/
		boolean isAll = false;
		if(StringUtil.isEmpty(productSearchKey) && StringUtil.isEmpty(minPrice) && StringUtil.isEmpty(maxPrice) && StringUtil.isEmpty(brandId) && StringUtil.isEmpty(brandIds)) {
			isAll = true;
		}
		
		try {
			// 【1】、查询所有商品类型
			List<ProductCategoryEntity> topCategoryList = productCategoryService.listProductCategoryForIndex(param);
			if (topCategoryList != null && topCategoryList.size() > 0) {
				for (ProductCategoryEntity category : topCategoryList) {
					if (StringUtil.isNotEmpty(category.getSubCategoryListStr())) {
						List<ProductCategoryEntity> tmpCategoryList = JSONArray.parseArray("[" + category.getSubCategoryListStr()+ "]", ProductCategoryEntity.class);
						category.setSubCategoryList(tmpCategoryList);
					}
				}
			}
			request.setAttribute("topCategoryList", topCategoryList);
			// 品牌列表
			List<ProductBrandEntity> brandList = null;
			hiddenParamMap.put("categoryId", productCategoryId);
			hiddenParamMap.put("searchKey", productSearchKey);
			// 【2】、关键字查询进入列表页面
			StringBuffer categoryIds = new StringBuffer("(");
			// 用于查询商品的分类合集
			StringBuffer productCategoryIds = new StringBuffer("(");
			if (null != categoryIdList && categoryIdList.size() > 0) {
				if(categoryIdList.size() == 1) {
					// 获取其所有的子集
					categoryIds.append(categoryIdList.get(0)).append(",");
					productCategoryIds.append(categoryIdList.get(0)).append(",");
					Map<String, Object> categoryParam = new HashMap<String, Object>();
					categoryParam.put("parentCategoryId", categoryIdList.get(0));
					List<ProductCategoryEntity> childCategoryList = productCategoryService.listProductCategory(categoryParam);
					if(null != childCategoryList && childCategoryList.size() > 0) {
						for (ProductCategoryEntity pc : childCategoryList) {
							productCategoryIds.append(pc.getId()).append(",");
                        }
					}
				} else {
					for (Long categoryId : categoryIdList) {
						categoryIds.append(categoryId).append(",");
						productCategoryIds.append(categoryId).append(",");
					}
				}
				categoryIds = new StringBuffer(categoryIds.substring(0, categoryIds.length() - 1)).append(")");
				productCategoryIds = new StringBuffer(productCategoryIds.substring(0, productCategoryIds.length() - 1)).append(")");
			}
			if (!isAll) {
				// 有关键字参数，没有商品分类参数
				// 那么商品分类则汇总所有已查询到的商品
				param.put("productName", productSearchKey);
				param.put("normalPro", "1");// 正常商品，过滤掉已下架商品
				param.put("brandCode", brandId);
				param.put("minPrice", minPrice);
				param.put("maxPrice", maxPrice);
				List<ProductEntity> proList = productService.listProduct(param);
				for (ProductEntity product : proList) {
					categoryIdList.add(product.getProductCategoryId());
				}
				param.put("categoryIdList", categoryIdList);
				if (categoryIdList.size() > 0) {
					if(categoryIdList.size() == 1) {
						// 获取其所有的子集
						categoryIds.append(categoryIdList.get(0)).append(",");
						productCategoryIds.append(categoryIdList.get(0)).append(",");
						Map<String, Object> categoryParam = new HashMap<String, Object>();
						categoryParam.put("parentCategoryId", categoryIdList.get(0));
						List<ProductCategoryEntity> childCategoryList = productCategoryService.listProductCategory(categoryParam);
						if(null != childCategoryList && childCategoryList.size() > 0) {
							for (ProductCategoryEntity pc : childCategoryList) {
								productCategoryIds.append(pc.getId()).append(",");
	                        }
						}
					} else {
						for (Long categoryId : categoryIdList) {
							categoryIds.append(categoryId).append(",");
							productCategoryIds.append(categoryId).append(",");
						}
					}
					categoryIds = new StringBuffer(categoryIds.substring(0, categoryIds.length() - 1)).append(")");
					productCategoryIds = new StringBuffer(productCategoryIds.substring(0, productCategoryIds.length() - 1)).append(")");
//					// 商品类型ids 查询参数
//					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
//					// 相关的商品分类列，用于商品列表页面展示
//					model.addAttribute("categoryList", categoryList);
//					for (Long categoryId : categoryIdList) {
//						categoryIds.append(categoryId).append(",");
//						productCategoryIds.append(categoryId).append(",");
//					}
//					categoryIds = new StringBuffer(categoryIds.substring(0, categoryIds.length() - 1)).append(")");
//					productCategoryIds = new StringBuffer(productCategoryIds.substring(0, productCategoryIds.length() - 1)).append(")");
					param.put("categoryIds", categoryIds.length() < 3 ? null : categoryIds.toString());
//					param.put("categoryIds", StringUtil.isNotEmpty(categoryIds) ? categoryIds.toString() : null);
					// 搜索相关品牌
//					brandList = productBrandService.listAllBrandForIndex(param);
					brandList = productBrandService.listAllBrandForWXIndex(param);
				}
				
				//查询筛选项
				/**
				 * 查询筛选项
				 */
				List<ProductCategoryPropertyFilterEntity> filterList = productCategoryPropertyFilterService.listProductCategoryPropertyFilterForIndex(param);
				if (filterList != null && filterList.size() > 0) {
					for (ProductCategoryPropertyFilterEntity filter : filterList) {
						if (StringUtil.isNotEmpty(filter.getPropertyValue())) {
							String[] pvs = filter.getPropertyValue().split(",");
							List<String> tmpList = new ArrayList<>();
							for (String pv : pvs) {
								tmpList.add(pv);
							}
							filter.setPropertyValueList(tmpList);
						}
					}
				}
				request.setAttribute("filterList", filterList);
			} else {
				// 无搜索条件，那就是初始化显示所有
				//品牌
				param.put("categoryIds", null);
				brandList = productBrandService.listAllBrandForWXIndex(param);
			}
			
			//排序
			param.put("sortField", sortField);
			param.put("sortType", sortType);
			
			// 查询品牌
			request.setAttribute("brandList", brandList);
			// key-value = brand_id-brand_name 方面页面显示品牌名称
			Map<Long, String> brandNameMap = new HashMap<Long, String>();
			if(brandList !=null && brandList.size() > 0){
				for (ProductBrandEntity brand : brandList) {
					if(StringUtil.isNotEmpty(brand.getSubBrandListStr())){
						List<ProductBrandEntity> subBrandList = JSONArray.parseArray("["+brand.getSubBrandListStr()+"]", ProductBrandEntity.class);
						brand.setSubBrandList(subBrandList);
						brand.setSubBrandListStr("["+brand.getSubBrandListStr()+"]");
					}
					brandNameMap.put(brand.getId(), brand.getBrandNameCh());
				}
				request.setAttribute("defaultSubBrandList", brandList.get(0).getSubBrandList());
			}
			// 品牌
			param.put("brandId", brandId);
			
			if (StringUtil.isNotEmpty(brandIds)) {
				param.put("brandIds", "(" + brandIds + ")");
				// 添加筛选条件
				StringBuffer brandBuf = new StringBuffer();
				for (String brandIdStr : brandIds.split(",")) {
					brandBuf.append(brandNameMap.get(Long.parseLong(brandIdStr)));
					requestParamMap.put(brandIdStr, "1");
				}
			}
			
			if (StringUtil.isNotEmpty(propertyFilter)) {
				List<ProductPropertyEntity> propertyList = JSONArray.parseArray(propertyFilter, ProductPropertyEntity.class);
				param.put("propertyList", propertyList);
				if(propertyList != null && propertyList.size() > 0){
					for (ProductPropertyEntity ppe : propertyList) {
						requestParamMap.put(ppe.getPropertyName(), ppe.getPropertyValue());
					}
				}
			} else {
				param.put("propertyList", Collections.EMPTY_LIST);
			}
			hiddenParamMap.put("propertyFilter", propertyFilter);
			// 【关键字查询】查询商品列表（模糊匹配商品名称 or 类型名称 or 品牌名称）
			// 【筛选项】品牌查询|类型查询|筛选项查询
			String pageNumStr = request.getParameter("pageNum");
			if(StringUtil.isEmpty(pageNumStr)){
				pageNumStr = "1";
			}
			int pageNum = Integer.parseInt(pageNumStr);
			int numPerPage = 20;
			PageParam pageParam = super.getPageParam(request);
			pageParam.setPageNum(pageNum);
			pageParam.setNumPerPage(numPerPage);

			param.put("categoryIds", productCategoryIds.length() < 3 ? null : productCategoryIds.toString());
			
			param.put("customerLevel", getCustomerLevel());
			param.put("isLogin", isLogin(request)? "1" : "0");
			param.put("searchKey", productSearchKey);
			param.put("customerId", getCustomerId());
			PageBean pageBean = productService.listProductPageForIndex(pageParam,param);
			// 格式化商品价格
			List<ProductEntity> productList = (List)pageBean.getRecordList();
			formatProductPrice(productList);
			// 如果是异步，直接写response
			if("sync".equals(requestType)){
				try {
					response.getWriter().write(JSONObject.toJSON(pageBean).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			request.setAttribute("productList", productList);
			request.setAttribute("pageBean", pageBean);
        } catch (Exception e) {
        	e.printStackTrace();
        }
		// 价格(最低价-最高价)
		param.put("minPrice", minPrice);
		param.put("maxPrice", maxPrice);
		
		hiddenParamMap.put("sortField", sortField);
		hiddenParamMap.put("sortType", sortType);
		hiddenParamMap.put("brandId", brandId);
		hiddenParamMap.put("brandIds", brandIds);
		hiddenParamMap.put("minPrice", minPrice);
		hiddenParamMap.put("maxPrice", maxPrice);
		request.setAttribute("searchKey", productSearchKey);
		request.setAttribute("requestParamMap", requestParamMap);
		request.setAttribute("sortField", sortField);
		request.setAttribute("sortType", sortType);
		request.setAttribute("minPrice", minPrice);
		request.setAttribute("maxPrice", maxPrice);
		request.setAttribute("propertyFilter", StringUtil.isNotEmpty(propertyFilter) ? propertyFilter.replace("\"", "'") : "");
		request.setAttribute("hiddenParamMap", hiddenParamMap);
		return "wx/product/product_list";
	}
	
	
	
	/**
	 * 微信端-商品详情页面
	 * @param request
	 * @return
	 * @author llp
	 */
	@RequestMapping("/detail")
	public String findProductDetail(HttpServletRequest request) {
		// 查询参数
		Map<String, Object> param = new  HashMap<String, Object>();
		// 【1】查询商品基本信息
		String productId = request.getParameter("productId");
		String productCode = request.getParameter("productCode");
		ProductEntity product = null;
		if(StringUtil.isNotNull(productId)) {
			param.put("productId", productId);
			product = productService.getProductById(Long.parseLong(productId));
		} else if(null == productId && StringUtil.isNotNull(productCode)) {
			product = productService.getProductByCode(productCode);
			productId = String.valueOf(product.getId());
			param.put("productId", productId);
		} else {
			// 没有ID,没有CODE，就返回空的商品对象
			product = new ProductEntity();
		}
		
		Map<String, Object> productDetailMap = new HashMap<String, Object>();
		/**
		 * key-object
		 * product_info 商品基本信息
		 * product_price 商品所有价格
		 * product_spec 商品规格
		 * product_composition 商品规格项组合
		 * product_property 商品详情属性
		 * produt_image 商品图片
		 * product_comment 商品评论
		 */
		// BigDecimal basePrice = product.getBasePrice();
		// 商品基本信息和详情
		productDetailMap.put("product_info", product);
		
		// 主商品价格 = 基价 + 客户差价
		BigDecimal productPrice = product.getBasePrice();
		BigDecimal marketProductPrice = product.getMarketPrice();
		
		// 【2】查询商品所有价格
		if(isLogin(request)){
			List<ProductPriceEntity> ppeList = productService.getProductPriceList(Long.parseLong(productId));
			productDetailMap.put("product_price", ppeList);
			String customerLevel = getCustomerLevel();
			if(ppeList != null && ppeList.size() > 0){
				for (ProductPriceEntity ppe : ppeList) {
					// 只取对应级别的价格
					if(ppe.getPriceLevel().equals(customerLevel)){
						productPrice = productPrice.add(ppe.getDiffPrice());
						marketProductPrice = marketProductPrice.add(ppe.getDiffPrice());
					}
				}
			}	
		}else{
			// 未登录使用游客价格
			productPrice = product.getTouristPrice();
		}
		
		
		// 【3】查询商品规格(包裹规格项的名称、值、价格)
		// 商品默认规格的价格
		BigDecimal defaultSpecPrice = new BigDecimal(0);
		List<ProductSpecRelaEntity> productSpecList = productService.listProductSpecPriceByProductId(param);
		if(productSpecList != null && productSpecList.size() > 0){
			for (ProductSpecRelaEntity productSpec : productSpecList) {
				if(StringUtil.isNotEmpty(productSpec.getProductSpecListStr())){
					List<ProductSpecRelaEntity> tmpSpecList = JSONArray.parseArray("["+productSpec.getProductSpecListStr()+"]", ProductSpecRelaEntity.class);
					productSpec.setProductSpecList(tmpSpecList);
					if(tmpSpecList != null && tmpSpecList.size() > 0){
						defaultSpecPrice = defaultSpecPrice.add(tmpSpecList.get(0).getSpecPrice());
					}
				}
			}
		}
		// 主商品价格
		request.setAttribute("mainProductPrice", productPrice);
		// 商品价格  基价+级别差价+默认规格价格
		request.setAttribute("productPrice", productPrice.add(defaultSpecPrice));
		productDetailMap.put("product_spec", productSpecList);
		request.setAttribute("hasSpec", productSpecList.size() > 0 ? "true":"false");
		
		// 【4】查询商品规格项组合
		// TODO 界面应该没有判断是否有这种组合，如果没有这种组合是不能购买的
		List<ProductSpecCompositionEntity> productSpecCmpList =  productService.listProductSpecCompostionByProductId(param);
		productDetailMap.put("product_composition", productSpecCmpList);
		
		// 【5】查询商品属性
		List<ProductPropertyRelaEntity> productPropertyList = productPropertyRelaService.listProductPropertyRela(Long.parseLong(productId));
		productDetailMap.put("product_property", productPropertyList);
		
		// 【6】查询商品图片
		List<ProductImageEntity> productImageList = productImageService.listProductImageForProductDetail(Long.parseLong(productId));
		if(productImageList != null && productImageList.size() > 0){
			for (ProductImageEntity productImage : productImageList) {
				if(1 == productImage.getImageType()){
					// 主图
					productDetailMap.put("product_main_image", productImage.getImagePath());
				}
			}
		}
		productDetailMap.put("product_image", productImageList);
		
		// 【7】查询商品产加的活动
		param.clear();
		List<String> productCodeList = new ArrayList<String>();
		productCodeList.add(product.getProductCode());
		param.put("productCodeList", productCodeList);
		param.put("productType", PromotionConstants.PROMOTION_PRODUCT_TYPE.NORMAL.getCode());
		// 批量查询结算商品参加了哪些活动
		List<PromotionProductEntity> ppList = promotionProductService.listPromotionProduct(param);
		// 数字格式化
		DecimalFormat numFormat = new DecimalFormat("#.00");
		if(ppList != null && ppList.size() > 0){
			for (PromotionProductEntity ppe : ppList) {
				PromotionRulesEntity promotionRules = promotionService.listPromotionRule(ppe.getPromotionId());
				PromotionEntity  promotionEntity = promotionRules.getPromtEntity();
				// 界面展示商品参加的活动
				List<PromotionEntity> promotionShowList = new ArrayList<PromotionEntity>();
				// 临时变量，组织活动描述信息
				StringBuffer promotionIntroBuf = new StringBuffer();
				if (PromotionConstants.PROMOTION_TYPE.REDUCE.getCode().equals(String.valueOf(promotionEntity.getPromotionType()))) {
					// 【1】满减
					// 取出满减规则列表
					List<PromotionRuleReduceEntity> reduceList = promotionRules.getReduceList();
					if (reduceList != null && reduceList.size() == 1) {
						// 只有一条记录，可能是无上限的递增式规则设置
						PromotionRuleReduceEntity reduce = reduceList.get(0);
						if (reduce.getIsLimit() == PromotionConstants.PROMOTION_RULE_LIMIT_TYPE.UNLIMTED.getCode()) {
							promotionIntroBuf.append("满").append(numFormat.format(reduce.getOrderMoney())).append("减")
								.append(numFormat.format(reduce.getReduceMoney())).append("(上不封顶)");
						} else {
							promotionIntroBuf.append("满").append(numFormat.format(reduce.getOrderMoney())).append("减")
								.append(numFormat.format(reduce.getReduceMoney()));
						}
						
					} else if (reduceList != null && reduceList.size() > 1) {
						// 大于1条，是有多条满减规则
						for (PromotionRuleReduceEntity reduce : reduceList) {
							if(reduceList.indexOf(reduce) == reduceList.size()-1){
								promotionIntroBuf.append("满").append(numFormat.format(reduce.getOrderMoney())).append("减")
									.append(numFormat.format(reduce.getReduceMoney()));
							}else{
								promotionIntroBuf.append("满").append(numFormat.format(reduce.getOrderMoney())).append("减")
									.append(numFormat.format(reduce.getReduceMoney())).append(",");
							}
						}
					}
					
					// 拼接满减活动的检查结果
					PromotionEntity  promotionShow = new PromotionEntity();
					promotionShow.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.REDUCE.getName());
					promotionShow.setPromotionIntro(promotionIntroBuf.toString());
					promotionShowList.add(promotionShow);
					
				} else if (PromotionConstants.PROMOTION_TYPE.GIFT.getCode().equals(String.valueOf(promotionEntity.getPromotionType()))) {
					// 【2】满赠活动
					// 取出满赠规则列表
					List<PromotionRuleGiftEntity> giftList = promotionRules.getGiftList();
					if (giftList != null && giftList.size() > 0) {
						// 循环满赠规则,一条购物车item最多只一满足一个(匹配金额的)规则
						for (PromotionRuleGiftEntity gift : giftList) {
							if (PromotionConstants.PROMOTION_GIFT_TYPE.GIFT.getCode().equals(gift.getGiftType())) {
								// 【2.1】赠品
								param.clear();
								param.put("promotionRuleId", gift.getId());
								param.put("productType", PromotionConstants.PROMOTION_PRODUCT_TYPE.GIFT.getCode());
								// 查询赠品
								List<PromotionProductEntity> giftProductList = promotionProductService.listPromotionProduct(param);
								if (giftProductList != null && giftProductList.size() > 0) {
									promotionIntroBuf.append("满").append(gift.getOrderMoney());
									for (PromotionProductEntity giftProduct : giftProductList) {
										if(giftProductList.indexOf(giftProduct) != giftProductList.size()){
											promotionIntroBuf.append("赠").append(giftProduct.getProductName()) 
												.append(" X ").append(giftProduct.getGiftNum())
												.append(",");
										}else{
											promotionIntroBuf.append("赠").append(giftProduct.getProductName())
												.append(" X ").append(giftProduct.getGiftNum());
										}
									}
									PromotionEntity  promotionShow = new PromotionEntity();
									promotionShow.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.GIFT.getName());
									promotionShow.setPromotionIntro(promotionIntroBuf.toString());
									promotionShowList.add(promotionShow);
								}
							} else if (PromotionConstants.PROMOTION_GIFT_TYPE.COUPON.getCode().equals(gift.getGiftType())) {
								// 【2.2】赠品优惠券
								
								long couponId = gift.getCouponId();
								CouponEntity  coupon = couponService.getCouponById(couponId);
								StringBuffer validity = new StringBuffer();
								if(coupon.getTimeType().equals(CouponConstants.TimeType.TIME_START_STOP)){
									validity.append(DateUtils.formatDate(coupon.getBeginTime())).append("~").append(DateUtils.formatDate(coupon.getEndTime()));
								}else{
									validity.append(coupon.getLimitDay()).append("天");
								}
								promotionIntroBuf.append("满").append(gift.getOrderMoney())
									.append("赠").append(coupon.getCouponName()).append(validity);
								PromotionEntity  promotionShow = new PromotionEntity();
								promotionShow.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.GIFT.getName());
								promotionShow.setPromotionIntro(promotionIntroBuf.toString());
								promotionShowList.add(promotionShow);
								
							} else if (PromotionConstants.PROMOTION_GIFT_TYPE.POINTS.getCode().equals(gift.getGiftType())) {
								// 【2.3】赠品积分
								promotionIntroBuf.append("满").append(gift.getOrderMoney())
									.append("赠").append(gift.getGiftValue()).append("积分");
								
								PromotionEntity  promotionShow = new PromotionEntity();
								promotionShow.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.GIFT.getName());
								promotionShow.setPromotionIntro(promotionIntroBuf.toString());
								promotionShowList.add(promotionShow);
							}
						}
					}
				} else if (PromotionConstants.PROMOTION_TYPE.DISCOUNT.getCode().equals(String.valueOf(promotionEntity.getPromotionType()))) {
					// 【3】折扣
					List<PromotionRuleDiscountEntity> discountList = promotionRules.getDiscountList();
					if (discountList != null && discountList.size() > 0) {
						for (PromotionRuleDiscountEntity discount : discountList) {
							
							if(discountList.indexOf(discount) == discountList.size()-1){
								promotionIntroBuf.append("满").append(discount.getOrderMoney()).append("打")
									.append(discount.getDiscount()).append("折");
							}else{
								promotionIntroBuf.append("满").append(discount.getOrderMoney()).append("打")
								.append(discount.getDiscount()).append("折").append(",");
							}
							PromotionEntity  promotionShow = new PromotionEntity();
							promotionShow.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.DISCOUNT.getName());
							promotionShow.setPromotionIntro(promotionIntroBuf.toString());
							promotionShowList.add(promotionShow);
						}
					}
				}
				request.setAttribute("promotionShowList", promotionShowList);
			}
		}
		
		// 商品详情
		request.setAttribute("productDetailMap", productDetailMap);
		
		//商品是否被收藏
		if(isLogin(request)){
			Long favoriteId = userFavoriteService.getCountByUserCodeAndProductId(getUserCode(), Long.parseLong(productId), null);
			request.setAttribute("favoriteId", favoriteId);
			// 加入足迹
			productBrowseRecordService.saveProductBrowseRecord(getUserCode(), Long.parseLong(productId));
		}

		

		// 查询商品评论
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("productCode", product.getProductCode());
		paramMap.put("isDelete", 1);
		// 是否有调价权限
		if(isLogin(request)){
			request.setAttribute("adjustPriceAuth", getCustomer().getAdjustPriceAuth());
		}
		
		PageParam pageParam = new PageParam(1, 5);
		PageBean evaluationPage = orderEvaluationService.listOrderEvaluationPage(pageParam, paramMap);
		request.setAttribute("evaluationPage", evaluationPage);
		
		// 查询微信调用接口信息
		String jsapi_ticket = WechatUtil.getJspiTicket();
		String url = request.getRequestURL().toString();
		String urlParam = request.getQueryString();
		if (StringUtil.isNotNull(urlParam)) {
			url = url + "?" + urlParam;
		}
		Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
		request.setAttribute("appId", WechatUtil.APPID);
		request.setAttribute("timestamp", sign.get("timestamp"));
		request.setAttribute("nonceStr", sign.get("nonceStr"));
		request.setAttribute("signature", sign.get("signature"));
		request.setAttribute("uuid", UUID.randomUUID().toString());
		
		return "wx/product/product_detail";
	}
	
	
	/**
	 * 查询单个单击的规格值
	 * @param request
	 * @return
	 */
	@RequestMapping("/listProductSpec")
	@ResponseBody
	public Map<String, Object> listProductSpec(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> param = new HashMap<String, Object>();
		String productId = request.getParameter("productId");
		param.put("productId", productId);
		
		try {
			// 【1】查询商品规格(包裹规格项的名称、值、价格)
			List<ProductSpecRelaEntity> productSpecList = productService.listProductSpecPriceByProductId(param);
			if(productSpecList != null && productSpecList.size() > 0){
				for (ProductSpecRelaEntity productSpec : productSpecList) {
					if(StringUtil.isNotEmpty(productSpec.getProductSpecListStr())){
						List<ProductSpecRelaEntity> tmpSpecList = JSONArray.parseArray("["+productSpec.getProductSpecListStr()+"]", ProductSpecRelaEntity.class);
						productSpec.setProductSpecList(tmpSpecList);
					}
				}
			}
			
			resultMap.put("product_spec", productSpecList);
			resultMap.put("has_spec", productSpecList.size() > 0 ? "true":"false");
					
			// 【1】查询商品规格项组合
			// TODO 界面应该没有判断是否有这种组合，如果没有这种组合是不能购买的
			List<ProductSpecCompositionEntity> productSpecCmpList =  productService.listProductSpecCompostionByProductId(param);
			resultMap.put("product_composition", productSpecCmpList);
		} catch (Exception e) {
			handleException("查询商品规格项失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 查询热点推荐商品列表
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月13日 下午3:38:45
	 */
	@RequestMapping("/listItemProduct")
	public String listItemProduct(HttpServletRequest request){
		Long parentId = Long.parseLong(request.getParameter("parentId"));
		Long moduleId = Long.parseLong(request.getParameter("moduleId"));
//		Long itemId = Long.parseLong("itemId");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("moduleId", moduleId);
		param.put("configType", "02");
		SiteModuleEntity moduleEntity = siteModuleService.getSiteModuleById(parentId);
		List<SiteConfigItemEntity> itemList = siteConfigItemService.listSiteConfigItem(param);
		List<Long> ids = new ArrayList<Long>();
		for (SiteConfigItemEntity itemEntity : itemList) {
			String[] productInfo = itemEntity.getProductCode().split("##");
			ids.add(Long.parseLong(productInfo[0]));
		}
        param.put("customerLevel", getCustomerLevel());
        param.put("isLogin", isLogin(request)? "1" : "0");
        param.put("customerId", getCustomerId());
        param.put("ids", ids);
        List<ProductEntity> productList = productService.listProductForSiteItem(param);
		formatProductPrice(productList);
		request.setAttribute("title", moduleEntity.getModuleName());
		request.setAttribute("productList", productList);

		// 查询微信调用接口信息
		String jsapi_ticket = WechatUtil.getJspiTicket();
		String url = request.getRequestURL().toString();
		String urlParam = request.getQueryString();
		if (StringUtil.isNotNull(urlParam)) {
			url = url + "?" + urlParam;
		}
		Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
		request.setAttribute("appId", WechatUtil.APPID);
		request.setAttribute("timestamp", sign.get("timestamp"));
		request.setAttribute("nonceStr", sign.get("nonceStr"));
		request.setAttribute("signature", sign.get("signature"));
		request.setAttribute("uuid", UUID.randomUUID().toString());
		param.put("configType", "01");
		List<SiteConfigItemEntity> titleList = siteConfigItemService.listSiteConfigItem(param);
		if (titleList.size() != 0) {
			titleList.get(0).setModuleName(moduleEntity.getModuleName());
			request.setAttribute("titleItem", titleList.get(0));
		}
		return "wx/product/product_item_list";
	}

	/**
	 * 异步查询商品评论
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月4日 上午10:20:42
	 */
	@RequestMapping("/queryProductEvaluation")
	@ResponseBody
	public Map<String, Object> queryProductEvaluation(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Long productId = Long.parseLong(request.getParameter("productId"));
		PageParam pageParam = getPageParam(request);
		try {
			ProductEntity product = productService.getProductById(productId);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("productCode", product.getProductCode());
			paramMap.put("isDelete", 1);
			PageBean evaluationPage = orderEvaluationService.listOrderEvaluationPage(pageParam, paramMap);
			resultMap.put("evaluationPage", evaluationPage);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			handleException("查询评论失败", logger, e);
		}
		return resultMap;
	}
}
